import { createRouter, createWebHistory } from 'vue-router'
import Store from '../store'
import system from './system'
const routes = [
    {
        path: '/',
        name: 'index',
        redirect: '/base',
        component: () => import('../views/index.vue'),
        children: [
            {
                path: '/base',
                name: 'baseHome',
                meta: { title: '首页' },
                component: () => import('../views/base.vue'),
            },
            ...system,
        ]
    },
    {
        path: '/login/:merNo',
        name: 'login',
        component: () => import('../views/login.vue')
    },
    {
        path: '/test',
        name: 'test',
        component: () => import('../views/test.vue')
    },
]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})

router.beforeEach((to, from, next) => {
    next()
})


const routerPush = router.push
const removeKeepAlive = (name) => {
    let index = Store.state.tabs.tabsList.findIndex(i => i.name == name)
    if (index > -1) {
        Store.commit('tabs/REMOVE_TABS_LIST', name)
    }
}

router.removeKeepAlive = removeKeepAlive
/**
 * url 跳转地址
 * reload 是否强制刷新keepAlive缓存，刷新后会重新走一遍生命周期，
 * 可选值：true, 或者 name
 * true的时候是在tabslist缓存name列表中寻找到路由对应的name，然后清空掉，如果找不到，说明没有缓存
 * name 直接传入需要清除换存档name
 * **/
router.push = (url, reload) => {
    if (reload) {
        if(typeof reload == 'boolean') {
            let toPath = url.slice(0, url.indexOf('?') > -1 ? url.indexOf('?') : void 0)
            let tabsList = Store.state.tabs.tabsList
            tabsList.forEach(item => {
                let tabsPath = item.path.slice(0, item.path.indexOf('?') > -1 ? item.path.indexOf('?') : void 0)
                if (tabsPath == toPath) {
                    removeKeepAlive(item.name);
                }
            })
        } else {
            removeKeepAlive(reload);
        }
    }
    routerPush(url)
}
// 关闭标签
router.removeTab = (name) => {
    let tabsList = Store.state.tabs.tabsList
    let index = tabsList.findIndex(i => i.name == name)
    let activeRoute = Store.state.tabs.activeRoute
    if (activeRoute.name == tabsList[index].name) {
        if (tabsList.length > 1) {
            let info;
            if (index == 0) {
                info = tabsList[index + 1]
            } else {
                info = tabsList[index - 1]
            }
            router.push(info.path)
        } else {
            router.push('/base')
            // this.returnHomePage()
        }
    }
    removeKeepAlive(name)
}

export default router
